package cn.turboinfo.fuyang.api.provider.mini.service.impl.session;

import cn.turboinfo.fuyang.api.domain.mini.service.session.MiniSessionService;
import cn.turboinfo.fuyang.api.entity.mini.exception.session.MiniSessionNotFoundException;
import cn.turboinfo.fuyang.api.entity.mini.pojo.session.MiniSession;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
@Service
public class MiniSessionServiceImpl implements MiniSessionService {

    private final StringRedisTemplate stringRedisTemplate;

    private String getSessionKey(String token) {
        return "mini_session_" + token;
    }

    @Override
    public Optional<MiniSession> findByToken(String token) {
        String sessionKey = getSessionKey(token);

        Boolean hasKey = stringRedisTemplate.hasKey(sessionKey);
        if (hasKey == null || !hasKey) {
            return Optional.empty();
        }

        HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();
        List<Object> multiGet = hashOperations.multiGet(sessionKey, Lists.newArrayList("userId"));

        MiniSession session = MiniSession
                .builder()
                .userId(Long.valueOf(String.valueOf(multiGet.get(0))))
                .build();

        return Optional.of(session);
    }

    @Override
    public void save(String token, MiniSession session) {
        HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();

        Map<String, String> sessionValueMap = new HashMap<>();
        sessionValueMap.put("userId", session.getUserId().toString());

        String sessionKey = getSessionKey(token);
        hashOperations.putAll(sessionKey, sessionValueMap);
        stringRedisTemplate.expire(sessionKey, 24, TimeUnit.HOURS);
    }

    @Override
    public void removeByToken(String token) {
        String sessionKey = getSessionKey(token);
        stringRedisTemplate.delete(sessionKey);
    }

    @Override
    public void refreshByToken(String token) {
        findByToken(token).ifPresent(session -> stringRedisTemplate.expire(getSessionKey(token), 24, TimeUnit.HOURS));
    }

    @Override
    public void validateByToken(String token) throws MiniSessionNotFoundException {
        findByToken(token).orElseThrow(MiniSessionNotFoundException::new);
    }

    @Override
    public MiniSession validateAndRefreshByToken(String token) throws MiniSessionNotFoundException {
        Optional<MiniSession> sessionOptional = findByToken(token);
        if (sessionOptional.isEmpty()) {
            throw new MiniSessionNotFoundException();
        }
        stringRedisTemplate.expire(getSessionKey(token), 24, TimeUnit.HOURS);
        return sessionOptional.get();
    }
}
